package com.srwl.mytx.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;

import com.github.florent37.viewanimator.ViewAnimator;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.adapter.PictureAdapter;
import com.srwl.mytx.fragment.PrivacyPolicyDialog_v1;
import com.srwl.mytx.utils.IMFileTools;
import com.srwl.mytx.utils.PreferenceManager;
import com.srwl.mytx.utils.Utils;
import com.srwl.mytx.widget.AgreementDialog;
import com.srwl.mytx.widget.PrivacyPolicyDialog;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 开屏页
 */
public class SplashActivity extends BaseActivity {
    private RelativeLayout rootLayout;
    private TextView versionText;

    private static int sleepTime = 2;
    // private View rl_warning;
    private TimerTask timerTask;
    private RecyclerView rv_introduce;
    private PictureAdapter pictureAdapter;
    List<String> picturesUrl = new ArrayList<>();
    private boolean isFirstOpenApp;
    private LinearLayout ll_logoContainer;
    private LinearLayout ll_dotContainer;
    private int lastSelectItemPosition;
    private Button btnContinue;


    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setContentView(R.layout.em_activity_splash);
        rootLayout = findViewById(R.id.splash_root);
        versionText = findViewById(R.id.tv_version);
        rv_introduce = findViewById(R.id.rv_introduce);
        ll_logoContainer = findViewById(R.id.ll_logo_container);
        ll_dotContainer = findViewById(R.id.ll_dot_container);
        btnContinue = findViewById(R.id.btn_continue);
        //versionText.setText(getVersion());
        AlphaAnimation animation = new AlphaAnimation(0.3f, 1.0f);
        animation.setDuration(1500);
        rootLayout.startAnimation(animation);


    }

    private void showPrivacyPolicyDialog() {
        PrivacyPolicyDialog agreement = new PrivacyPolicyDialog(this);
        agreement.setCanceledOnTouchOutside(false);
        agreement.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                // finish();
                moveTaskToBack(false);
            }
        });

        agreement.setConfirmListener(new PrivacyPolicyDialog.ConfirmListener() {
            @Override
            public void onConfirmListener() {
                PreferenceManager.getInstance().setIsFirstOpenApp(false);
                sleepTime = 1;
                startCount();
            }
        });
        agreement.show();
        //控制dialog 的宽高，必须放在 show 之后
        WindowManager.LayoutParams params = agreement.getWindow().getAttributes();//获取对话框当前的参数值
        params.height =  WindowManager.LayoutParams.WRAP_CONTENT;
        params.width = (screenWidth);
        agreement.getWindow().setAttributes(params);

//        PrivacyPolicyDialog_v1 authorityFragment = PrivacyPolicyDialog_v1.newInstance();
//        authorityFragment.show(getSupportFragmentManager(), "");
    }

    private void initRecyclerView() {
        int normalSize = Utils.dpToPx(15, this);
        PagerSnapHelper pagerSnapHelper = new PagerSnapHelper() {
            @Override
            public int findTargetSnapPosition(RecyclerView.LayoutManager layoutManager, int velocityX, int velocityY) {
                int targetSnapPosition = super.findTargetSnapPosition(layoutManager, velocityX, velocityY);
                if (targetSnapPosition < 0 || targetSnapPosition > picturesUrl.size() - 1) {
                    return targetSnapPosition;
                }
                View lastItem = ll_dotContainer.getChildAt(lastSelectItemPosition);
                lastItem.setBackgroundResource(R.drawable.circle_gray_shape);
                ViewGroup.LayoutParams layoutParams1 = lastItem.getLayoutParams();
                layoutParams1.width = normalSize;
                lastItem.setLayoutParams(layoutParams1);
                lastSelectItemPosition = targetSnapPosition;
                View child = ll_dotContainer.getChildAt(targetSnapPosition);
                if (child == null) {
                    return targetSnapPosition;
                }
                child.setBackgroundResource(R.drawable.circle_write_shape);

                if (targetSnapPosition == picturesUrl.size() - 1) {
                    btnContinue.setVisibility(View.VISIBLE);
                } else {
                    btnContinue.setVisibility(View.GONE);
                }
                return targetSnapPosition;
            }
        };
        pagerSnapHelper.attachToRecyclerView(rv_introduce);
        picturesUrl.add("https://mytx-app.oss-cn-beijing.aliyuncs.com/mytx_01.png");
        picturesUrl.add("https://mytx-app.oss-cn-beijing.aliyuncs.com/mytx_02.png");
        picturesUrl.add("https://mytx-app.oss-cn-beijing.aliyuncs.com/mytx_03.png");
        picturesUrl.add("https://mytx-app.oss-cn-beijing.aliyuncs.com/mytx_04.png");
        for (int i = 0; i < picturesUrl.size(); i++) {
            View dot = new View(this);
            if (i == 0) {
                dot.setBackgroundResource(R.drawable.circle_write_shape);
            } else {
                dot.setBackgroundResource(R.drawable.circle_gray_shape);
            }
            ViewGroup.LayoutParams layoutParams = new LinearLayout.LayoutParams(normalSize, normalSize);
            dot.setLayoutParams(layoutParams);
            ll_dotContainer.addView(dot);
        }
        pictureAdapter = new PictureAdapter(this, picturesUrl);
        rv_introduce.setAdapter(pictureAdapter);
        rv_introduce.setLayoutManager(new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false));
        btnContinue.setOnClickListener(v -> startActivity(new Intent(SplashActivity.this, MainActivity.class)));
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (PreferenceManager.getInstance().isFirstOpenApp()) {//第一次打开APP
            showPrivacyPolicyDialog();
        } else {
            startCount();
        }
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
    }

    /**
     * 增加游客模式，直接进入主页面
     */
    private void startCount() {
        final Timer timer = new Timer();
        timerTask = new TimerTask() {
            @Override
            public void run() {

                if (sleepTime > 0) {
                    sleepTime--;
                } else {
//                    startActivity(new Intent(SplashActivity.this, MainActivity.class));
//                    finish();
                    timer.cancel();
                    if (isFirstOpenApp) {
                        runOnUiThread(() -> {
                            ll_logoContainer.setVisibility(View.INVISIBLE);
                            rv_introduce.setVisibility(View.VISIBLE);
                        });
                    } else {

                        if (Helper.getInstance().isLoggedIn()) {
                            startActivity(new Intent(SplashActivity.this, MainActivity.class));
                            finish();
                        } else {
                            startActivity(new Intent(SplashActivity.this, LoginActivity.class));
                            finish();
                        }
                    }
                }
            }
        };
        timer.schedule(timerTask, 0, 1000);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timerTask != null) {
            timerTask.cancel();
            timerTask = null;
        }
    }
}
